// index.js
const api = require('../../utils/api.js')

Page({
  data: {
    adminInfo: null,
    stats: null,
    permissions: null,
    showPermissions: false
  },

  onLoad() {
    this.getAdminInfo()
    this.getStats()
    this.getAdminPermissions()
  },

  onShow() {
    this.getStats()
  },

  // 获取管理员信息
  getAdminInfo() {
    const adminInfo = wx.getStorageSync('adminInfo')
    if (adminInfo) {
      this.setData({
        adminInfo: adminInfo
      })
    }
  },

  // 获取管理员权限
  async getAdminPermissions() {
    try {
      const adminInfo = wx.getStorageSync('adminInfo')
      if (!adminInfo || !adminInfo.id) {
        console.log('没有管理员信息，无法获取权限')
        return
      }

      const app = getApp()
      const globalData = app ? app.globalData : { token: '', baseUrl: '' }
      
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: globalData.baseUrl + '/getAdminDetail',
          method: 'GET',
          data: { id: adminInfo.id },
          header: {
            'content-type': 'application/json',
            'Authorization': globalData.token ? 'Bearer ' + globalData.token : ''
          },
          success: (res) => {
            if (res.statusCode === 200) {
              resolve(res.data)
            } else {
              reject(res)
            }
          },
          fail: reject
        })
      })
      
      if (res.code === 1) {
        console.log('=== 管理员权限详情 ===')
        console.log('原始权限数据:', res.data.rule_list)
        
        // 解析权限数据
        let permissions = {}
        if (res.data.rule_list && Array.isArray(res.data.rule_list)) {
          res.data.rule_list.forEach(rule => {
            const parts = rule.split('/')
            if (parts.length === 2) {
              const module = parts[0]
              const action = parts[1]
              
              if (!permissions[module]) {
                permissions[module] = []
              }
              if (!permissions[module].includes(action)) {
                permissions[module].push(action)
              }
            }
          })
        }
        
        console.log('解析后的权限数据:', permissions)
        
        // 显示每个模块的权限
        Object.keys(permissions).forEach(module => {
          console.log(`模块 ${module}:`, permissions[module])
        })
        
        // 转换为适合WXML显示的格式
        const permissionsList = Object.keys(permissions).map(module => ({
          key: module,
          value: permissions[module]
        }))
        
        console.log('转换后的权限列表:', permissionsList)
        
        this.setData({
          permissions: permissionsList
        })
      } else {
        console.error('获取权限失败:', res.msg)
      }
    } catch (error) {
      console.error('获取权限出错:', error)
    }
  },

  // 切换权限显示
  togglePermissions() {
    this.setData({
      showPermissions: !this.data.showPermissions
    })
  },

  // 获取统计数据
  getStats() {
    // 这里可以调用API获取统计数据
    // 暂时使用模拟数据
    this.setData({
      stats: {
        totalOrders: 25,
        pendingAllocations: 8,
        pendingReports: 12,
        pendingActiveReports: 5,
        totalWorkers: 15,
        totalProductionPlans: 12,
        activeProductionPlans: 6
      }
    })
  },

  // 跳转到订单管理
  goToOrders() {
    wx.navigateTo({
      url: '/pages/orders/orders'
    })
  },

  // 跳转到订单进度
  goToOrderProgress() {
    wx.navigateTo({
      url: '/pages/order-progress/order-progress'
    })
  },

  // 跳转到分工管理
  goToAllocationManage() {
    wx.navigateTo({
      url: '/pages/allocation-manage/allocation-manage'
    })
  },

  // 跳转到报工审核
  goToReports() {
    wx.navigateTo({
      url: '/pages/reports/reports'
    })
  },

  // 跳转到主动报工审核
  goToActiveReports() {
    wx.navigateTo({
      url: '/pages/active-reports/active-reports'
    })
  },

  // 跳转到创建分工
  goToCreateAllocation() {
    wx.navigateTo({
      url: '/pages/create-allocation/create-allocation'
    })
  },

  // 跳转到生产计划管理
  goToProductionPlans() {
    wx.navigateTo({
      url: '/pages/production-plans/production-plans'
    })
  },

  // 跳转到创建生产计划
  goToCreateProductionPlan() {
    wx.navigateTo({
      url: '/pages/create-production-plan/create-production-plan'
    })
  },

  // 跳转到从订单生成生产计划
  goToGenerateProductionPlan() {
    wx.navigateTo({
      url: '/pages/generate-production-plan/generate-production-plan'
    })
  },

  // 跳转到生产大屏
  goToBigScreen() {
    wx.navigateTo({
      url: '/pages/production-bigscreen/production-bigscreen'
    })
  },

  // 跳转到每日工作报工管理
  goToDailyWorkReport() {
    wx.navigateTo({
      url: '/pages/admin-daily-work-report/admin-daily-work-report'
    })
  },

  // 跳转到待质检列表
  goToQualityPending() {
    wx.navigateTo({
      url: '/pages/quality-pending/quality-pending'
    })
  },

  // 跳转到质检记录
  goToQualityRecords() {
    wx.navigateTo({
      url: '/pages/quality-records/quality-records'
    })
  },

  // 跳转到质检标准
  goToQualityStandards() {
    wx.navigateTo({
      url: '/pages/quality-standards/quality-standards'
    })
  },

  // 跳转到质检统计
  goToQualityStatistics() {
    wx.navigateTo({
      url: '/pages/quality-statistics/quality-statistics'
    })
  },

  // 跳转到产品管理
  goToProducts() {
    wx.navigateTo({
      url: '/pages/products/products'
    })
  },

  // 跳转到型号管理
  goToProductModels() {
    wx.navigateTo({
      url: '/pages/product-models/product-models'
    })
  },

  // 跳转到工序管理
  goToProcesses() {
    wx.navigateTo({
      url: '/pages/processes/processes'
    })
  },

  // 跳转到工价管理
  goToProcessPrices() {
    wx.navigateTo({
      url: '/pages/process-prices/process-prices'
    })
  },

  // 跳转到工序员工关联管理
  goToProcessUsers() {
    wx.navigateTo({
      url: '/pages/process-users/process-users'
    })
  },

  // 跳转到管理员管理
  goToAdminManage() {
    wx.navigateTo({
      url: '/pages/admin-manage/admin-manage'
    })
  },

  // 跳转到用户管理
  goToUserManage() {
    wx.navigateTo({
      url: '/pages/user-manage/user-manage'
    })
  },

  // 退出登录
  logout() {
    wx.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          // 清除本地存储
          wx.removeStorageSync('adminInfo')
          wx.removeStorageSync('token')
          
          // 清除全局数据
          const app = getApp()
          app.globalData.adminInfo = null
          app.globalData.token = ''
          
          // 跳转到登录页
          wx.reLaunch({
            url: '/pages/login/login'
          })
        }
      }
    })
  }
}) 